package cn.xiaopengstack.domain.trade.rule.trade;

import cn.xiaopengstack.domain.activity.model.entity.GroupBuyActivityEntity;
import cn.xiaopengstack.domain.activity.repository.IActivityRepository;
import cn.xiaopengstack.domain.trade.rule.factory.TradeRuleFilterFactory;
import cn.xiaopengstack.domain.trade.model.entity.TradeRuleCommandEntity;
import cn.xiaopengstack.domain.trade.model.entity.TradeRuleResponseEntity;
import cn.xiaopengstack.domain.trade.repository.ITradeRepository;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author jiangyangang
 */
@Component
@Slf4j
public class UserTakeLimitRuleFilter extends AbstractTradeLogicLink<TradeRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeRuleResponseEntity> {

    public UserTakeLimitRuleFilter(ITradeRepository groupBuyOrderRepository, IActivityRepository activityRepository) {
        super(groupBuyOrderRepository, activityRepository);
    }

    @Override
    public TradeRuleResponseEntity apply(TradeRuleCommandEntity request, TradeRuleFilterFactory.DynamicContext dynamic) throws Exception {
        log.info("交易规则过滤-用户参与次数校验。userId={} activityId={}", request.getUserId(), request.getActivityId());

        Integer userTakeOverActivityCount = activityRepository.queryOrderCountByActivityId(request.getActivityId(), request.getUserId());
        GroupBuyActivityEntity groupBuyActivityEntity = dynamic.getGroupBuyActivityEntity();
        Integer takeLimitCount = groupBuyActivityEntity.getTakeLimitCount();
        if (Objects.nonNull(takeLimitCount) && takeLimitCount <= userTakeOverActivityCount) {
            throw new AppException(ResponseCode.TRADE_COUNT_LIMITED.getCode(), ResponseCode.TRADE_COUNT_LIMITED.getInfo());
        }

        dynamic.setUserTakeOverActivityCount(userTakeOverActivityCount);

        return next(request, dynamic);
    }
}
